import db from "../utils/db";
import supabaseService from "./supabaseService";
import quizHistoryService from "./quizHistoryService";

export const quizService = {
    async getQuizzes(chapterTitle:string) {
        try {
            const transaction = db.transaction('quizzes', 'readonly');
            const store = transaction.objectStore('quizzes');
            const index = store.index('chapterTitle');
            const result = await index.getAll(chapterTitle);
            if (result.length > 0) {
                return result;
            }
            const { data, error } = await supabaseService.getSupabase()
                .from('quiz')
                .select('*')
                .eq('basic_info->>chapter_title', chapterTitle);
            if (error) {
                throw error;
            }
            const transaction2 = db.transaction('quizzes', 'readwrite');
            const store2 = transaction2.objectStore('quizzes');
            for (const quiz of data) {
                store2.add(quiz);
            }
            return data;
        } catch (error) {
            console.error('Error fetching quizzes:', error);
            return null;
        }
    },
    async getQuizList(chapterTitle:string) {
        const data = await quizService.getQuizzes(chapterTitle);
        const quizzes = data?.reduce((acc, item) => {
            try {
                const itemQuizzes = JSON.parse(item.content);
                itemQuizzes.forEach((quiz: any) => {
                    quiz.basic_info = item.basic_info;
                });
                return acc.concat(itemQuizzes);
            } catch (error) {
              console.error('Error parsing quiz content:', error, item.content, item.basic_info);
              return acc;
            }
          }, []);
          return quizzes;
    },
    async getQuizByTitle(quizTitle: string) {
        try {
            const transaction = db.transaction('quizzes', 'readonly');
            const store = transaction.objectStore('quizzes');
            const index = store.index('quizTitle');
            const result = await index.get(quizTitle);
            if (result) {
                return result;
            }
        } catch (error) {
            console.error('Error fetching quiz:', error);
        }
    },
    async getTopQuizzes(chapterTitle:string, quizAmount: number = 5) {
        const quizList = await this.getQuizList(chapterTitle)
        let allHistory:any[] = await quizHistoryService.getHistory(chapterTitle);
        const now = Date.now();
        const questionWithScore = quizList.map((q:any) => {
            let h = allHistory.find(h => h.content.quizTitle === q.question);
            let score = 0;
            if (!h) {
                score += 2; // 新题
            } else {
                h = h.content;
                const due = h.nextReviewAt < now;
                if (due) score += 3;
                const lastCorrect = h.history[h.history.length - 1]?.correct;
                if (!lastCorrect) score += 2;
                const daysSince = (now - h.lastReviewed) / (1000 * 3600 * 24);
                if (daysSince > 7) score += 1;
                score -= (h.proficiency ?? 50) / 50; // 熟练度越高越少出
            }
            return { ...q, score };
        });

        const topQuizzes = questionWithScore
            .sort((a:any, b:any) => b.score - a.score)
            .slice(0, quizAmount);

        return { topQuizzes, allHistory, quizAmount: questionWithScore.length };
    },
    // 获取当天做题的记录
    async getDailyProgress() {
        const allHistory = await db.getAll('quizHistory');
        return allHistory;
    }
}

  